'''
Created on 2010-10-29

@author: Administrator
'''
import config
from util import DB
from datetime import datetime
import fileinput
import re
_lineRegex = re.compile(r'([^ ]*) ([^ ]*) ([^ ]*) \[([^\]]*)\] "([^"]*)" (\d+) ([^ ]*)')
class ApacheLogLine:
    """A Python class whose attributes are the fields of Apache log line.
    CLF format only
    127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326
    would have the following field values as an ApacheLogLine:

    ip = '127.0.0.1'
    ident = '-'
    http_user = 'frank'
    time = '10/Oct/2000:13:55:36 -0700'
    request_line = 'GET /apache_pb.gif HTTP/1.0'
    http_response_code = '200'
    http_response_size = 2326
    http_method = 'GET'
    url = '/apache_pb.gif'
    http_vers = 'HTTP/1.0'
    """
    #l depends on myf's db
    def __init__(self, l):
#        self.ip, self.ident, \
#        self.http_user, self.time, \
#        self.request_line, self.http_response_code, \
#        self.http_response_size = l
#        self.http_method, self.url, self.http_vers = self.request_line.split()
#        self.date = datetime.strptime(self.time.split()[0], '%d/%b/%Y:%H:%M:%S')
#        if self.http_response_size.isdigit():
#            self.http_response_size = 'null'
            
        self.ip,self.ident,self.http_user,self.url,self.date,\
        self.http_response_size = l
        self.http_method="GET"
        self.http_vers = "HTTP1.1"
        self.http_response_code="200"
#        if not (self.http_response_size.isdigit()):
#            self.http_response_size = 'null'
            
            
class loglines:
    ###to code. 
    def __init__(self, tblname):
        """Instantiating an connection to database which record log lines"""
        self.conn = DB.getConn()
        self.cur = self.conn.cursor()
        self.count = self.cur.execute("select * from %s" %(tblname) )
        

    ###to code: yield entries from database
    def __iter(self):
        """Returns a log line object for each iteration. """
        failcount = 0
        for line in self.f:
            try:
                m = _lineRegex.match(line.strip())
                if m == None:
                    continue
                log_line = ApacheLogLine(m.groups())
            except ValueError,AttributeError:
                print line
                failcount+=1
                print failcount
                continue                
            yield log_line
            
    def __iter__(self):
        for i in range(self.count):
            t = self.cur.fetchone()
            log_line = ApacheLogLine(t[1:])
            yield log_line
        